<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Log;

/**
 * 用户回答单位题目 次数表
 */

class AnswerActivityUnitUserNumber extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_unit_user_number';


    /**
     * 获取单位答题次数,如果是轮次答题，就是轮次次数
     * @param $user_guid 用户id
     * @param $act_id 活动id
     * @param $unit_id 图书馆id
     */
    public function getUnitAnswerNumber($user_guid, $act_id, $unit_id = null, $date = null)
    {
        return $this->where('user_guid', $user_guid)
            ->where('act_id', $act_id)
            ->where(function ($query) use ($unit_id, $date) {
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                }
                if ($date) {
                    $query->where('date', $date);
                }
            })->sum('number');
    }

    /**
     * 写入单位答题记录
     */
    public function addUnitNumber($act_id,$unit_id,$user_guid){
        $unit_id = $unit_id ?: 0;
        $res = $this->where('act_id' , $act_id)
                    ->where('unit_id' , $unit_id)
                    ->where('user_guid' , $user_guid)
                    ->where('date' , date('Y-m-d'))
                    ->first();
        if($res){
            $res->number = $res->number + 1;
            return $res->save();
        }
        $this->act_id = $act_id;
        $this->unit_id = $unit_id;
        $this->user_guid = $user_guid;
        $this->date = date('Y-m-d');
        $this->number = 1;

        return $this->save();
    }

}
